import pygame
from pygame.locals import *
import sys
from airplane_sprites import *

#  飞机大战游戏初始化
pygame.init()  # 初始化pygame
# 背景图片
background = pygame.image.load('./images/background.png')  # 加载背景图片
bg_rect = background.get_rect()

# 设置窗口
size = width, height = bg_rect.width, bg_rect.height
pygame.display.set_caption("飞机大战游戏V1.0.0")
screen = pygame.display.set_mode(size)

# 英雄图片
hero = pygame.image.load("./images/hero1.png")
hero_rect = hero.get_rect()
hero_position = hr_x_axis, h_y_axis = (size[0] - hero_rect.width)/2, (size[1] - hero_rect.height)

# 创建敌机精灵
enemy1 = GameSprite('enemy1.png', speed=5)
enemy2 = GameSprite('enemy2.png', (100, 0))
# 创建敌机精灵组
enemy_group = pygame.sprite.Group(enemy1, enemy2)
# 开始按钮图片
start_play = pygame.image.load("./images/start.png")
start_position = st_x_axis, st_y_axis = (size[0] - hero_rect.width - 174)/2, (size[1] - hero_rect.height)/2
# 初始化图像
screen.blit(background, (0, 0))  # 显示背景
screen.blit(hero, hero_position)  # 显示英雄
screen.blit(start_play, start_position)  # 显示
# enemy_group.update()  # 更新敌机位置
# enemy_group.draw(screen)  # 显示敌机
pygame.display.flip()

# 初始化时钟对象
clock = pygame.time.Clock()

# 初始化英雄位置、移动距离
hero_x = hero_position[0]  # 初识x
hero_y = hero_position[1]  # 初识y
move_distance = 5  # 每次移动距离/px

# 保持窗口
while True:
    # 事件检测
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        # 键盘方向键控制英雄移动
        if event.type == pygame.KEYDOWN:
            if event.key == K_UP:
                hero_y -= move_distance
            elif event.key == K_RIGHT:
                hero_x += move_distance
            elif event.key == K_DOWN:
                hero_y += move_distance
            elif event.key == K_LEFT:
                hero_x -= move_distance
            # 边界检测
            if hero_x <= 0:
                hero_x = 0
            elif hero_x >= (bg_rect.width - hero_rect.width):
                hero_x = (bg_rect.width - hero_rect.width)
            if hero_y <= 0:
                hero_y = 0
            elif hero_y >= (bg_rect.height - hero_rect.height):
                hero_y = (bg_rect.height - hero_rect.height)
    clock.tick(60)  # 帧率60/s
    screen.blit(background, (0, 0))  # 显示背景
    screen.blit(hero, (hero_x, hero_y))  # 显示英雄
    enemy_group.update()  # 更新敌机位置
    enemy_group.draw(screen)  # 显示敌机
    pygame.display.update()
    pass  # TODO 未完成

pygame.quit()  # 结束pygame
